package com.spring.core.wired;

import com.spring.core.annotation.Value;
import com.spring.core.context.AbstractApplicationContext;
import com.spring.core.context.AnnotationApplicationContext;
import com.spring.core.context.ApplicationContext;
import com.spring.core.mapping.HandlerMapping;

import java.lang.reflect.Field;

/**
 * autowired 注解注入
 *
 * @author Zee
 * @version 1.0
 * @date 2021/10/13
 */
public class FieldValueWired implements Wired {


    @Override
    public void doWired(AbstractApplicationContext context) {
        System.out.println("依赖注入:@value");
        context.getIoc().forEach((k, v) -> {
            Field[] fields = v.getClass().getDeclaredFields();
            for (Field field : fields) {
                //字段上面包含Autowired注解和设置值
                if (field.isAnnotationPresent(Value.class)) {
                    Value value = field.getAnnotation(Value.class);
                    String beanName = value.value();
                    if ("".equals(beanName)) {
                        beanName = field.getName();
                    }
                    try {
                        //强制访问权限
                        field.setAccessible(true);
                        field.set(v, context.getProperties().getProperty(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

        });

    }
}
